<template>
    <div class="jobBooking">
        <div class="tabHeader">
            <el-tabs v-model="editableTabsValue" @tab-click="handleTabClick">
                <el-tab-pane v-for="(item,index) in editableTabs" :key="item.id" :name="item.name" :label="item.name">
                    <span slot="label">
                        <el-popover placement="bottom-start" popper-class='custom'>
                            <span slot="reference">{{item.name}}</span>
                            <div class="secondGroup">
                                <div class="item-card" v-for="(i,index) in secondGroupInfo.typeCountData"
                                    :key="i.optionValue" :class="{active:activeValue === i.optionValue}"
                                    @click="handleSecondGroup(i,secondGroupInfo,item)">
                                    <i class="iconfont icon-caiyouduo_hemaixiangqing-fanganxiangqing icon"
                                        style="font-size:18px"></i>
                                    <span class="groupName">{{i.optionName}}</span>
                                    <span class="groupName" style="margin-left:8px">{{i.optionNum}}</span>
                                </div>
                            </div>
                        </el-popover>
                    </span>
                </el-tab-pane>
            </el-tabs>

            <div class="setBtn">
                <my-button type='primary' plain size='mini' class='el-icon-circle-check'
                    @btnClick='$refs.saveScheme.showDialog()'>
                    保存当前
                </my-button>
                <my-button type='primary' size='mini' class='el-icon-edit-outline'
                    @btnClick='$refs.scheme.drawerOpen()'>
                    筛选方案
                </my-button>
            </div>
        </div>

        <!-- 动态表单 -->
        <dynamic-form :formDataList='formDataList' @getFormData='getFormData' ref='dynamicForm'></dynamic-form>

        <!-- 按钮操作 -->
        <custom-setbtn>
            <template #l_btn>
                <div class="l_btn">
                    <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline"
                        @click="$router.push('/productionManagement/jobBooking/create')">创建报工</el-button>
                    <el-dropdown trigger="click">
                        <el-button type="primary" size="mini" icon="el-icon-s-operation" :disabled='isBatchCheck'
                            style='margin:0 10px'>批量操作
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-document" @click='batchVer'>批量审批
                                </el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-refresh-right" @click='batchFlash'>
                                    批量刷新绩效</el-button>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <el-button type="primary" size="mini" icon="el-icon-upload2" plain @click='getWorkReportExport'
                        :disabled='computedTotal'>导出
                    </el-button>
                    <el-button type="primary" size="mini" icon="el-icon-download" plain
                        @click="openDialog('importMould')">导入</el-button>
                    <el-button type="text" size="mini" icon="el-icon-document"
                        @click="$router.push('/productionManagement/jobBooking/loadLog')">查看导入日志</el-button>
                    <el-button type="text" size="mini" icon="el-icon-edit"
                        @click="$router.push('/productionManagement/jobBooking/customEvent')">自定义事件</el-button>
                </div>
            </template>
            <template #r_btn>
                <div class="r_btn">
                    <el-button type="text" size="mini" icon="el-icon-time" @click='operateDrawer'>操作记录</el-button>

                    <!-- 列配置表格 -->
                    <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup'>
                    </pop-checkbox>
                </div>
            </template>
        </custom-setbtn>

        <!-- 导入 -->
        <import-mould title='报工' ref='importMould' @importSuccess="importSuccess"></import-mould>

        <!-- 操作记录 -->
        <el-drawer title="操作记录" :visible.sync="drawer" direction="rtl" size='550px'>
            <el-table :data="operateRecordTable" border style="width: 100%;"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}" max-height='560'>
                <el-table-column prop="handleTime" label="操作时间" width='160'>
                </el-table-column>
                <el-table-column prop="handleName" label="操作用户" width='80'>
                </el-table-column>
                <el-table-column prop="handleType" label="操作类型" width='100'>
                </el-table-column>
                <el-table-column label="操作详情">
                    <template slot-scope="scope">
                        <div style='height:80px;overflow:auto' class='scroll'>
                            {{scope.row.handleDetail}}
                        </div>
                    </template>
                </el-table-column>
                <div slot="empty">
                    <el-empty :image-size='100'></el-empty>
                </div>
            </el-table>
            <el-pagination v-if="total" @current-change="handleCurrentChange" :page-size="operateParams.limit"
                layout="prev, pager, next" :total='total' background>
            </el-pagination>
        </el-drawer>

        <!-- 保存当前 -->
        <save-current ref="saveScheme" @getList='getList' :editableTabs='allTabs'
            @fromOutDrawerClose='fromOutDrawerClose'></save-current>

        <!-- 筛选方案--创建方案 -->
        <operate-scheme ref="scheme" :editableTabs='allTabs' @getList='getList' @fromOutDrawerClose='fromOutDrawerClose'
            @lastData='lastData'></operate-scheme>

        <!-- 表格 -->
        <table-list :tableGroup='tableGroup' @getCheckedId='getCheckedId' :searchForm='formDataList.searchForm'
            @getTotal='getTotal' @getSecondGroupInfo="getSecondGroupInfo" ref='tableList'>
        </table-list>
    </div>
</template>

<script>
    import {
        handleLogList
    } from '@/api/produceController'
    import {
        productColumns
    } from '@/api/customFieldController'
    import {
        screenPlanList
    } from '@/api/produceController'
    import tableList from './tableList.vue'
    import dynamicForm from '@/components/dynamicForm'
    import commonDialog from './dialog.vue'
    import saveCurrent from './saveCurrent.vue'
    import operateScheme from './operateScheme.vue'
    export default {
        data() {
            return {
                editableTabsValue: '',
                editableTabs: [],
                allTabs: [],
                fromSavaCurrent: 0,
                isMounted: '',
                secondGroupInfo: [],
                activeValue: 'all',
                isCollapse: false,
                customFieldMap: {},
                searchForm: {
                    customFieldMap: {},
                    searchOther: {},
                    page: 1,
                    limit: 10,
                },
                formDataList: {
                    formGroup: [{
                            label: 'workOrderCode',
                            name: '工单编号',
                            prop: '',
                            placeholder: '请输入工单编号',
                            key: 'srk',
                            defaultCode: ''
                        },
                        {
                            label: 'productCode',
                            name: '产品编号',
                            prop: '',
                            placeholder: '请输入产品编号',
                            key: 'srk'
                        },
                        {
                            label: 'productName',
                            name: '产品名称',
                            prop: '',
                            placeholder: '请输入产品名称',
                            key: 'srk'
                        },
                        {
                            label: 'productSpecification',
                            name: '产品规格',
                            prop: '',
                            placeholder: '请输入产品规格',
                            key: 'srk'
                        },
                        {
                            label: 'userIds',
                            name: '生产人员',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sci',
                            dataUrl: {
                                url: '/user/user_list_o',
                                value: 'id'
                            }
                        },
                        {
                            label: 'processState',
                            name: '工序状态',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sel',
                            node: {
                                default: [],
                                isRadio: false,
                                options: [{
                                        value: 0,
                                        label: '未开始'
                                    },
                                    {
                                        value: 1,
                                        label: '执行中'
                                    },
                                    {
                                        value: 2,
                                        label: '已结束'
                                    },
                                    {
                                        value: 3,
                                        label: '已取消'
                                    },
                                ]
                            }
                        },
                        {
                            label: 'processName',
                            name: '工序名称',
                            prop: '',
                            placeholder: '请输入工序名称',
                            key: 'srk'
                        },
                        {
                            label: 'processCode',
                            name: '工序编号',
                            prop: '',
                            placeholder: '请输入工序编号',
                            key: 'srk',
                            defaultCode: ''
                        },
                        {
                            label: ['reportStartTimeStart', 'reportStartTimeEnd'],
                            name: '报工开始时间',
                            prop: '',
                            key: 'dpi'
                        },
                        {
                            label: ['reportEndTimeStart', 'reportEndTimeEnd'],
                            name: '报工结束时间',
                            prop: '',
                            key: 'dpi'
                        },
                        {
                            label: ['actualReportStartTime', 'actualReportEndTime'],
                            name: '实际报工时间',
                            prop: '',
                            key: 'dpi'
                        },
                        {
                            label: 'verifyState',
                            name: '审批状态',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sel',
                            node: {
                                default: '',
                                isRadio: true,
                                options: [{
                                        value: 1,
                                        label: '未审批'
                                    },
                                    {
                                        value: 2,
                                        label: '已审批'
                                    },
                                ]
                            }
                        },
                        {
                            label: 'pricingMethod',
                            name: '计价方式',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sel',
                            node: {
                                default: '',
                                isRadio: true,
                                options: [{
                                        value: 1,
                                        label: '计件'
                                    },
                                    {
                                        value: 2,
                                        label: '计时'
                                    },
                                ]
                            }
                        },
                    ],
                    searchForm: {
                        workOrderCode: '',
                        productCode: '',
                        productName: '',
                        productSpecification: '',
                        userIds: [],
                        processState: [],
                        processName: '',
                        processCode: '',
                        reportStartTimeStart: '',
                        reportStartTimeEnd: '',
                        reportEndTimeStart: '',
                        reportEndTimeEnd: '',
                        actualReportStartTime: '',
                        actualReportEndTime: '',
                        verifyState: '',
                        pricingMethod: '',
                        page: 1,
                        limit: 10
                    },
                    formSet: true,
                    type: 'workReport'
                },
                tableGroup: [],
                disposeGroup: [],
                drawer: false,
                operateRecordTable: [],
                operateParams: {
                    page: 1,
                    limit: 8,
                    type: 1
                },
                total: 0,
                tableTotal: 0,
                ids: '',
            }
        },
        components: {
            dynamicForm,
            tableList,
            commonDialog,
            saveCurrent,
            operateScheme,
        },
        computed: {
            isBatchCheck() {
                return this.ids.length <= 0
            },
            computedTotal() {
                return this.tableTotal <= 0
            }
        },
        watch: {
            tableTotal(total) {
                //当表格数据为空时 列配置和表头无自定义字段信息
                if (total <= 0) {
                    this.tableGroup = this.utils.filterCustomFields(this.tableGroup)
                    this.disposeGroup = this.utils.filterCustomFields(this.disposeGroup)
                }
            }
        },
        created() {         
            if (this.$store.state.router === this.$route.path) {
                this.searchForm.page = this.$store.state.page || 1;
            }   
            const {
                code,
                processCode
            } = this.$route.query
            if (code && processCode) {
                const {
                    formGroup,
                    searchForm
                } = this.formDataList
                formGroup.find(i => i.label == 'workOrderCode').defaultCode = code
                formGroup.find(i => i.label == 'processCode').defaultCode = processCode
                searchForm.workOrderCode = code
                searchForm.processCode = processCode
            }
        },
        mounted() {            
            this.isMounted = 'mounted'
            this.getProductColumns({
                type: 'workReport'
            })
            this.getScreenPlanList({
                type: 4
            })
        },
        methods: {
            getProductColumns: async function (data) {
                const res = await productColumns(data)
                if (res.code == 200) {
                    this.disposeGroup = []
                    this.tableGroup = []
                    res.data.map((item, i) => {
                        const key = {
                            index: '80',
                            productSpecification: '70',
                            productName: '130',
                            workOrderCode: '155',
                            productCode: '150',
                            verifyState: '70',
                            processState: '70',
                            reportNumber: '70',
                            pricingMethod: '70',
                            unitPrice: '70',
                            expectWages: '70',
                            goodProductNumber: '70',
                            badProductNumber: '90',
                            produceUserName: '70',
                            reportStartTime: '145',
                            reportEndTime: '145',
                            verifyTime: '145'
                        }
                        let width = key[item.name] ?? '180'
                        if (item.state) {
                            this.tableGroup.push({
                                label: item.name,
                                name: item.chineseName,
                                width
                            })
                        }
                        this.disposeGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            state: item.state
                        })
                    })
                }
            },
            //监视复选框值变化
            handleChangeDiposeGroup(disposeGroup) {
                let configureList = []
                configureList = disposeGroup.map(i => {
                    return {
                        name: i.label,
                        chineseName: i.name,
                        state: i.state
                    }
                })
                this.getProductColumns({
                    type: 'workReport',
                    configureList
                }).then(() => {
                    this.$refs.tableList.updateTable()
                })
            },
            getTotal(total) {
                this.tableTotal = total
            },
            //获取勾选中表格的id
            getCheckedId(ids) {
                this.ids = ids
            },
            //点击查询获取表单数据
            getFormData(val) {
                this.searchForm.page = 1
                this.handleFormData(val)
                this.$refs.tableList.getWorkReportList(this.searchForm)
            },
            //处理非筛选方案表单项自定义和非自定义字段数据
            handleFormData(val) {
                this.searchForm.searchOther = {}
                this.customFieldMap = {}
                for (const key in val) {
                    /**
                     * 自定义字段表单数据放在searchOther中的customFieldMap对象中
                     * 其中计数器--日期选择器--多选框以 `[自定义字段id]:'arr[0],arr[1]'` 形式传给后端
                     * 其它类型表单项以`[自定义字段id]:'value' 形式传给后端
                     */
                    if (!isNaN(parseFloat(key)) && isFinite(key)) {
                        let str = ''
                        if (Array.isArray(val[key])) {
                            val[key].forEach(k => str += k + ',')
                            if (str.length > 0) str = str.substr(0, str.length - 1)
                        }
                        this.customFieldMap[key] = Array.isArray(val[key]) ? str : val[key]
                        this.searchForm.searchOther.customFieldMap = this.customFieldMap
                    } else { //非自定义字段表单数据放在searchOther对象中
                        this.searchForm.searchOther[key] = val[key]
                    }
                }
                //点击查询按钮时需要将筛选方案表单项数据和非筛选方案表单项数据同时接收，做合并查询
                if (this.editableTabs.length) {
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.handleSchemeData(findTab)
                }
            },
            //获取筛选方案列表
            getList(payload) {
                this.fromSavaCurrent = payload == undefined || payload.length
                this.getScreenPlanList({
                    type: 4
                }, payload == undefined || {
                    delIndex: payload.delIndex,
                    name: payload.name
                })
            },
            handleTabClick(tab) {
                this.searchForm.page = 1;
                this.activeValue = 'all'
                const target = this.editableTabs.find(i => i.name == tab.label)
                this.schemeClick(target)
            },
            //获取二级分组信息
            getSecondGroupInfo(payload) {
                const {
                    typeCountData
                } = payload
                typeCountData.unshift({
                    optionName: "全部",
                    optionValue: "all"
                })
                this.secondGroupInfo = payload
            },
            //处理二级分组
            handleSecondGroup(group, secondGroupInfo) {
                const {
                    optionValue
                } = group
                const {
                    key
                } = secondGroupInfo
                this.activeValue = optionValue
                this.searchForm.page = 1
                this.searchForm.secondSearchCondition = {
                    conditionName: optionValue === 'all' ? undefined : key,
                    conditionValue: optionValue === 'all' ? undefined : optionValue
                }
                this.$refs.tableList.getWorkReportList(this.searchForm)
            },
            //筛选方案列表
            getScreenPlanList(data, p) {
                screenPlanList(data, p).then(res => {
                    if (res.code == 200) {
                        this.editableTabs = res.data.filter(i => i.isValid)
                        this.allTabs = res.data
                        if (!res.data.length) return //初始化进入页面时若无筛选方案不调用列表接口
                        /**
                         *  创建第一条筛选方案时tabs下划线默认选中，
                            当超过一条时，点击到第n个筛选方案，此时打开drawer再关闭tabs下划线默认为第n个
                         */
                        if (res.data.length && res.data.length == 1) this.editableTabsValue = res.data[0].name
                        /**
                         * 当选中第n个tabs标签页，此时打开筛选方案删除当前第n条数据时，tabs下划线默认向前移动一位
                         */
                        if (p != undefined && p.delIndex && p.name == this.editableTabsValue) {
                            this.editableTabsValue = res.data[p.delIndex - 1].name
                        }
                        /**
                         * 保存当前 || 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         * isMounted : 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         *             当创建第二条以上时将isMounted = '' 不需要再调用列表接口
                         */
                        if (this.fromSavaCurrent === 1 || this.isMounted == 'mounted') {
                            if (this.$store.state.tab && this.$store.state.router === this.$route.path) {
                                this.schemeClick(JSON.parse(this.$store.state.tab));
                            } else {
                                this.schemeClick(res.data[0]);
                            }
                        }
                    }
                })
            },
            //关闭筛选方案列表
            fromOutDrawerClose() {
                if (this.editableTabs.length) { //当没有筛选方案时不需要调用列表接口
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.schemeClick(findTab)
                }
            },
            //删除筛选方案最后一条数据时
            lastData() {
                let payload = {
                    searchOther: {},
                    page: 1,
                    limit: 10,
                }
                this.$refs.tableList.getWorkReportList(payload)
            },
            //tabs标签页--popover框
            schemeClick(item) {
                this.$store.commit('setRouter', this.$route.path);
                this.$store.commit('setTab', JSON.stringify(item));
                this.searchForm = { //多个筛选方案互相切换先置空
                    customFieldMap: {},
                    searchOther: {},
                    screenPlanId: item.id,
                    page: this.searchForm.page,
                    limit: 10,
                }
                this.isMounted = ''
                /**
                 * getValue 这个方法单独获取已填写的非筛选方案表单项的数据
                 * 若通过selectData获取会触发'getFormData'导致每次点击筛选方案tabs标签重复调用列表接口
                 */
                let formDataPayload = this.$refs.dynamicForm.getValue()
                this.handleSchemeData(item)
                this.handleFormData(formDataPayload)
                this.$refs.tableList.getWorkReportList(this.searchForm)
            },
            //处理筛选方案表单项自定义和非自定义字段数据
            handleSchemeData(item) {
                let screenCondition = []
                let payload = {}
                screenCondition = JSON.parse(item.screenCondition).configData
                screenCondition.forEach(i => {
                    if (i.fieldId == 'reportStart' || i.fieldId == 'reportEnd') {
                        payload[i.fieldId + 'TimeStart'] = i.fieldValue[0]
                        payload[i.fieldId + 'TimeEnd'] = i.fieldValue[1]
                    } else if(i.fieldId == 'actualReport'){
                        payload[i.fieldId + 'StartTime'] = i.fieldValue[0]
                        payload[i.fieldId + 'EndTime'] = i.fieldValue[1]
                    }else if (i.type != undefined && i.type != 'selectRadio' && i.type != 'ipt') {
                        payload[i.fieldId] = i.fieldValue.toString()
                    } else {
                        payload[i.fieldId] = i.fieldValue
                    }
                })
                this.editableTabsValue = item.name
                for (const key in payload) {
                    if (!isNaN(parseFloat(key)) && isFinite(key)) {
                        this.searchForm.customFieldMap[key] = payload[key]
                    } else {
                        this.searchForm[key] = payload[key]
                    }
                }
            },
            //打开相对应的dialog
            openDialog(way) {
                let obj = {
                    type: 'workReport',
                    importUrl: '/produce/work_report_import',
                    isCover: false
                }
                this.$refs[way].openDialog(obj)
            },
            // 导入成功
            importSuccess() {
                this.$refs.tableList.getWorkReportList(this.formDataList.searchForm)
            },
            //批量审批
            batchVer() {
                this.$refs.tableList.getUpdateState({
                    ids: this.ids
                })
            },
            //批量刷新绩效
            batchFlash() {
                this.$confirm('确认批量刷新绩效？操作后将重新计算绩效工资，刷新后不可恢复', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    showClose: false,
                    type: 'warning'
                }).then(() => {
                    this.$refs.tableList.getFlashPerformance({
                        ids: this.ids
                    })
                }).catch(e => {})
            },
            //操作记录
            getHandleLogList(data) {
                handleLogList(data).then(res => {
                    if (res.code == 200) {
                        this.operateRecordTable = res.data.records
                        this.total = res.data.total
                    }
                })
            },
            //打开操作记录抽屉
            operateDrawer() {
                this.drawer = true
                this.getHandleLogList(this.operateParams)
            },
            //currentPage 改变时会触发
            handleCurrentChange(val) {
                this.operateParams.page = val
                this.getHandleLogList(this.operateParams)
            },
            //报工导出
            getWorkReportExport() {
                let enumProps = {
                    pricingMethod: {
                        0: '计件',
                        1: '计时'
                    },
                    processState: {
                        0: '未开始',
                        1: '执行中',
                        2: '已结束',
                        3: '已取消'
                    },
                    verifyState: {
                        0: '未审批',
                        1: '已审批'
                    }
                }
                this.$refs.tableList.getTableData(
                    this.formDataList.searchForm,
                    '/produce/work_report_list',
                    '报工' + new Date().dateFormat('yyyyMMddhhmmss'),
                    1,
                    enumProps
                )
            },
        },
    }
</script>

<style lang="less" scoped>
    .jobBooking {
        overflow: auto;

        .tabHeader {
            height: 44px;
            background-color: rgb(250, 250, 250);
            padding-left: 10px;

            .el-tabs {
                float: left;
                max-width: 1000px;
            }

            /deep/ .el-tabs__header {
                margin: 0;
                padding-top: 4px;
            }

            /deep/ .el-tabs__nav-wrap::after {
                opacity: 0;
            }

            /deep/ .el-tabs__item {
                padding: 0 10px;
            }

            /deep/ .el-tabs__item:first-child {
                padding-left: 0px;
            }

            /deep/ .el-tabs__item:last-child {
                padding-right: 0px;
            }


            /deep/ .el-tabs__nav {
                height: 40px;
            }

            /deep/ .el-tabs__nav-next,
            /deep/ .el-tabs__nav-prev {
                line-height: 38px;
            }

            .setBtn {
                float: right;
                margin-top: 8px;
                margin-right: 20px;
            }
        }

        /deep/ th.el-table__cell.gutter {
            background-color: #fafafa;
        }

        /deep/ label.el-radio {
            margin-right: 20px;
        }

        /deep/ .el-dialog__body {
            padding: 10px 30px 10px 30px;

            .descriptions {
                font-size: 14px;
                color: rgb(0, 0, 0, .85);
                margin-bottom: 20px;
            }

            .editDescriptions {
                margin: 20px 0px 5px;
                padding: 10px;
                background-color: rgb(250, 250, 250);
                color: rgb(153, 153, 153);
                border-radius: 2px;
                font-size: 12px;

                p {
                    margin-bottom: 4px;
                }

                p:last-child {
                    margin-bottom: 0;
                }
            }
        }


        .iconfont.icon-wenhao {
            margin-left: 10px;
        }
    }
</style>